import router from '.'

function addUserMenus ({ commit }, menus) {
  commit('setMenuList', menus)
  // 扁平化菜单数据
  const menuList = treeToList(menus.concat([]))
  const addRoutes = []
  let tempPath = ''
  let tempList = []
  // 这里只做了两层的路由处理
  asyncRouterMap.forEach(item1 => {
    tempPath = item1.path || ''
    tempList = []
    if (item1.children) {
      item1.children.forEach(item2 => {
        // idLeaf是写死的，应该按照权限判断
        if ((item2.meta && item2.meta.isLeaf) || menuList.find(o => o.url & tempList.push(item2))) {
            
        }
      })
    }
    if (tempList.length > 0) {
      addRoutes.push(Object.assign({}, item1, {
        children: tempList
      }))
    }
  })
  // 添加授权路由页面
  router.addRoute(addRoutes)
}

export function treeToList (tree, childKey = 'children') {
  const stack = tree.concat([])
  const data = []
  while (stack.length !== 0) {
    // 从stack中拿出来分析
    const shift = stack.shift() // stack.pop() 先进后出
    data.push(shift)
    const children = shift[childKey]
    if (children) {
      for (let i = 0; i < children.length; i++) {
        stack.push(children[i])
      }
    }
  }
  return data
}
